﻿//-----------------------------------------------------------------------
// <copyright file="EnumExtensions.cs" company="SLWY Enterprises">
// * Copyright (C) 2017 四川商旅无忧科技有限公司 版权所有。
// * version : 1.0
// * author  : qinchaoyue
// * FileName: EnumExtensions.cs
// * history : created by qinchaoyue 2017-11-10 09:36:57
// </copyright>
//-----------------------------------------------------------------------

namespace Slwy.Utility.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;

    /// <summary>
    /// 枚举扩展类
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// 获取枚举项上的<see cref="DescriptionAttribute"/>特性的文字描述
        /// </summary>
        /// <param name="value">枚举</param>
        /// <returns>属性值</returns>
        public static string ToDescription(this Enum value)
        {
            var type = value.GetType();
            var member = type.GetMember(value.ToString()).FirstOrDefault();
            return member != null ? member.ToDescription() : value.ToString();
        }

        /// <summary>
        /// 把枚举转换为键值对集合
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <returns>以枚举值为key，枚举文本为value的键值对集合</returns>
        public static Dictionary<int, string> ToDictionary(this Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new ArgumentException(@"传入的参数必须是枚举类型！", "enumType");
            }
            var enumDic = new Dictionary<int, string>();
            var enumValues = Enum.GetValues(enumType);
            foreach (Enum enumValue in enumValues)
            {
                var key = Convert.ToInt32(enumValue);
                var value = enumValue.ToDescription();
                enumDic.Add(key, value);
            }
            return enumDic;
        }
    }
}
